import 'dart:convert';

import 'package:dio/dio.dart';
/**
 * 提现页面
 * author wim
 */

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
// import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_yres/tool/constant.dart';
// import 'package:panda/base/SignType.dart';
import 'package:flutter_yres/tool/application.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/pages/user/BindZfb.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import 'package:flutter_yres/tool/LoadingUtil.dart';
import 'package:flutter_yres/tool/md5_sign.dart';
import 'package:flutter_yres/pages/event/GetCardEven.dart';
import './BalanceChange.dart';
import 'package:flutter_yres/tool/Toast.dart';
import 'package:flutter_yres/tool/BlankToolBarTool.dart';
import 'SetPayPwd.dart';

class DrawMoneyPage extends StatefulWidget {
  String total = "0.0";
  DrawMoneyPage({Key key, @required this.total}) : super(key: key);

  @override
  _DrawMoneyPageState createState() => _DrawMoneyPageState();
}

class _DrawMoneyPageState extends State<DrawMoneyPage>
    with WidgetsBindingObserver {
  String money = "";
  String account = "";
  String name = "";
  String token = "";
  BlankToolBarModel barModel = BlankToolBarModel();
  ScrollController scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text(
          '余额提现',
          style: TextStyle(
              color: black,
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
        ),
        backgroundColor: white,
        brightness: Brightness.light,
        elevation: 0.2,
        iconTheme: IconThemeData(color: black_99),
      ),
      body: BlankToolBarTool.blankToolBarWidget(context,
          model: barModel,
          body: Container(
              child: SingleChildScrollView(
            controller: scrollController,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(
                    left: ScreenUtil.getInstance().setHeight(DP_40),
                    top: ScreenUtil.getInstance().setHeight(DP_20),
                    right: ScreenUtil.getInstance().setHeight(DP_20),
                  ),
                  child: Text('提现至支付宝',
                      style: TextStyle(
                          color: black,
                          fontSize:
                              ScreenUtil.getInstance().setSp(BIG_FONT_SIZE))),
                ),
                // Container(
                //   child: Row(
                //     mainAxisAlignment: MainAxisAlignment.center,
                //     children: <Widget>[
                //       ClipOval(
                //           child: Container(
                //         width: ScreenUtil.getInstance().setHeight(DP_80),
                //         height: ScreenUtil.getInstance().setHeight(DP_80),
                //         color: white,
                //         child: Image.asset(
                //           "images/app_icon.png",
                //           fit: BoxFit.fill,
                //         ),
                //       )),
                //       Container(padding: EdgeInsets.all(20),child: Text('----------->')),
                //       ClipOval(
                //         child: Container(
                //             color: white,
                //             width: ScreenUtil.getInstance().setHeight(DP_80),
                //             height: ScreenUtil.getInstance().setHeight(DP_80),
                //             child: Image.asset("images/icon_ipay.png",
                //                 fit: BoxFit.fill)),
                //       ),
                //     ],
                //   ),
                // ),
                Container(
                    child: Row(
                      children: <Widget>[
                        Text('提现账号       ',
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE))),
                        Expanded(
                          child: Text('$account',
                              style: TextStyle(
                                  color: Colors.black54,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE))),
                        ),
                        new Container(
                          width: ScreenUtil.getInstance().setWidth(DP_180),
                          height: ScreenUtil.getInstance().setHeight(DP_40 + 5),
                          margin: EdgeInsets.fromLTRB(0, 0, 0, 8),
                          decoration: new BoxDecoration(
                              color: mainColor,
                              borderRadius: BorderRadius.circular(20.0)),
                          child: new FlatButton(
                            child: new Padding(
                              padding: EdgeInsets.all(0.0),
                              child: new Text(
                                "修改账号",
                                style: new TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(SMALL_FONT_SIZE)),
                              ),
                            ),
                            onPressed: () {
                              Navigator.of(context).push<String>(
                                  new MaterialPageRoute(builder: (context) {
                                return new BindZfbPage(type: '');
                              })).then((value) {
                                if (value != null) {
                                  print(value);
                                  account = value.split(';')[0];
                                  name = value.split(';')[1];
                                  // setState(() {});
                                }
                              });
                            },
                          ),
                        ),
                        // GestureDetector(
                        //   child: Text("修改账号",
                        //       style: TextStyle(
                        //           color: mainColor,
                        //           fontSize: ScreenUtil.getInstance()
                        //               .setSp(NORMAL_FONT_SIZE))),
                        //   onTap: () {

                        //   },
                        //   behavior: HitTestBehavior.opaque,
                        // )
                      ],
                    ),
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(DP_20),
                        ScreenUtil.getInstance().setHeight(DP_20),
                        ScreenUtil.getInstance().setHeight(DP_20),
                        ScreenUtil.getInstance().setHeight(DP_10)),
                    decoration: BoxDecoration(
                        color: white, borderRadius: BorderRadius.circular(0)),
                    margin: EdgeInsets.only(
                      left: ScreenUtil.getInstance().setHeight(DP_20),
                      top: ScreenUtil.getInstance().setHeight(DP_20),
                      right: ScreenUtil.getInstance().setHeight(DP_20),
                    )),
                Container(height: 1),
                Container(
                    child: Row(
                      children: <Widget>[
                        Text('真实姓名       ',
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE))),
                        Expanded(
                          child: Text('$name',
                              style: TextStyle(
                                  color: Colors.black54,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE))),
                        ),
                        GestureDetector(
                          child: Text("",
                              style: TextStyle(
                                  color: mainColor,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE))),
                          onTap: () {
                            money = widget.total;
                            setState(() {});
                          },
                          behavior: HitTestBehavior.opaque,
                        )
                      ],
                    ),
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(DP_20),
                        ScreenUtil.getInstance().setHeight(DP_20),
                        ScreenUtil.getInstance().setHeight(DP_20),
                        ScreenUtil.getInstance().setHeight(DP_20)),
                    decoration: BoxDecoration(
                        color: white, borderRadius: BorderRadius.circular(0)),
                    margin: EdgeInsets.only(
                      left: ScreenUtil.getInstance().setHeight(DP_20),
                      right: ScreenUtil.getInstance().setHeight(DP_20),
                    )),
                Container(
                  width: double.infinity,
                  decoration: BoxDecoration(
                      color: white, borderRadius: BorderRadius.circular(0)),
                  padding:
                      EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
                  margin: EdgeInsets.all(
                    ScreenUtil.getInstance().setHeight(DP_20),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text('输入提现金额'+'(提现收取5%的手续费)',
                          style: TextStyle(
                              color: black,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE))),
                      Row(
                        children: <Widget>[
                          Text(MONEY,
                              style: TextStyle(
                                  color: black,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(BIG_FONT_SIZE * 2 - 15))),
                          Expanded(
                            child: TextField(
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(BIG_FONT_SIZE * 2 - 15),
                                  color: black),
                              keyboardType: TextInputType.number,
                              maxLines: 1,
                              controller: TextEditingController.fromValue(
                                  TextEditingValue(
                                      text: money, //判断keyword是否为空
                                      // 保持光标在最后

                                      selection: TextSelection.fromPosition(
                                          TextPosition(
                                              affinity: TextAffinity.downstream,
                                              offset: money.length)))),
                              minLines: 1,
                              cursorColor: mainColor,
                              onChanged: (value) {
                                money = value;
                              },
                              keyboardAppearance: Brightness.light,
                              decoration: new InputDecoration(
                                contentPadding: EdgeInsets.all(5),
                                hintText: "0.00",
                                border: InputBorder.none,
                                hintStyle: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(BIG_FONT_SIZE * 2),
                                    color: Colors.black45),
                              ),
                            ),
                          ),
                          GestureDetector(
                            child: Text("全部提现",
                                style: TextStyle(
                                    color: Colors.blue,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(SMALL_FONT_SIZE))),
                            onTap: () {
                              money = widget.total;
                              setState(() {});
                            },
                            behavior: HitTestBehavior.opaque,
                          )
                        ],
                      ),
                      Divider(
                        height: 1.0,
                        indent: 0.0,
                        color: grey,
                      ),
                      Container(
                        height: 10,
                      ),
                      Row(
                        children: <Widget>[
                          Text('本次最多可提现  ',
                              style: TextStyle(
                                  color: black,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE))),
                          Text(widget.total,
                              style: TextStyle(
                                  color: mainColor,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE))),
                        ],
                      )
                    ],
                  ),
                ),
                // Padding(
                //   padding:
                //       EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_30)),
                //   child: Text('余额提现至',
                //       style: TextStyle(
                //           color: black,
                //           fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE))),
                // ),
                // Container(
                //   width: double.infinity,
                //   padding:
                //       EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
                //   margin: EdgeInsets.fromLTRB(
                //       ScreenUtil.getInstance().setHeight(DP_20),
                //       0,
                //       ScreenUtil.getInstance().setHeight(DP_20),
                //       ScreenUtil.getInstance().setHeight(DP_20)),
                //   decoration: BoxDecoration(
                //       color: white, borderRadius: BorderRadius.circular(15)),
                //   child: Column(
                //     children: <Widget>[
                //       Row(
                //         children: <Widget>[
                //           Image.asset(
                //             "images/icon_ipay.png",
                //             scale: 1.5,
                //           ),
                //           Container(
                //             width: 10,
                //           ),
                //           Expanded(
                //             child: Text('支付宝',
                //                 style: TextStyle(
                //                     color: black,
                //                     fontSize: ScreenUtil.getInstance()
                //                         .setSp(NORMAL_FONT_SIZE))),
                //           ),
                //           CircularCheckBox(
                //               value: pay_way == "alipay",
                //               activeColor: mainColor,
                //               inactiveColor: black_99,
                //               materialTapTargetSize: MaterialTapTargetSize.padded,
                //               onChanged: (bool x) {
                //                 if (pay_way == "wechat") {
                //                   pay_way = "alipay";
                //                 }
                //                 setState(() {});
                //               }),
                //         ],
                //       ),
                //       //       Container(
                //       //         height: 5,
                //       //       ),
                //       //       Divider(
                //       //         height: 1.0,
                //       //         indent: 0.0,
                //       //         color: grey,
                //       //       ),
                //       //       Container(
                //       //         height: 5,
                //       //       ),
                //       //       Row(
                //       //         children: <Widget>[
                //       //           Image.asset(
                //       //             "images/icon_wechat.png",
                //       //             scale: 1.5,
                //       //           ),
                //       //           Container(
                //       //             width: 10,
                //       //           ),
                //       //           Expanded(
                //       //             child: Text('微信',
                //       //                 style: TextStyle(
                //       //                     color: black,
                //       //                     fontSize: ScreenUtil.getInstance()
                //       //                         .setSp(NORMAL_FONT_SIZE))),
                //       //           ),
                //       //           CircularCheckBox(
                //       //               value: pay_way == "wechat",
                //       //               activeColor: mainColor,
                //       //               inactiveColor: black_99,
                //       //               materialTapTargetSize: MaterialTapTargetSize.padded,
                //       //               onChanged: (bool x) {
                //       //                 if (pay_way == "alipay") {
                //       //                   pay_way = "wechat";
                //       //                 }
                //       //                 setState(() {});
                //       //               }),
                //       //         ],
                //       //       ),
                //     ],
                //   ),
                // ),
                new Container(
                  width: double.infinity,
                  margin:
                      EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_40)),
                  height: ScreenUtil.getInstance().setWidth(DP_90),
                  decoration: new BoxDecoration(
                      color: mainColor,
                      borderRadius: BorderRadius.circular(DP_80)),
                  padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
                  child: new FlatButton(
                    child: new Padding(
                      padding: EdgeInsets.all(0.0),
                      child: new Text(
                        "立即提现",
                        style: new TextStyle(
                            color: Colors.white,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE)),
                      ),
                    ),
                    onPressed: () {
                      if (account == '') {
                        Toast.toast(context, msg: "请先绑定提现账号");
                        // Fluttertoast.showToast(msg: "请先绑定提现账号");
                        return;
                      }
                      showDialog(
                          context: context,
                          barrierDismissible: false,
                          builder: (_) {
                            return new NetLoadingDialog(
                              loadingText: "提现中...",
                              bgColor: Color.fromARGB(255, 0, 0, 0),
                              requestCallBack: null,
                              outsideDismiss: false,
                            );
                          });
                      put();
                    },
                  ),
                ),
                new Container(
                  width: double.infinity,
                  margin:
                      EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_40)),
                  height: ScreenUtil.getInstance().setWidth(DP_90),
                  decoration: new BoxDecoration(
                      color: Colors.red,
                      borderRadius: BorderRadius.circular(DP_80)),
                  padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
                  child: new FlatButton(
                    child: new Padding(
                      padding: EdgeInsets.all(0.0),
                      child: new Text(
                        "互转",
                        style: new TextStyle(
                            color: Colors.white,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE)),
                      ),
                    ),
                    onPressed: () {
                      isTX();
                    },
                  ),
                )
              ],
            ),
          ))),
    );
  }

  isTX() async {
    FormData data = new FormData.fromMap({'token': token});
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + '/app.php?c=UserBalance&a=isSetDrawPwd',
        data: data);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    print(userMap);
    Toast.toast(context, msg: msg);
    if (msg == '已设置') {
      Navigator.of(context)
          .push<String>(new MaterialPageRoute(builder: (context) {
        return new BanlanceChangePage();
      }));
    } else if (msg.contains('未设置')) {
      //未设置
      Navigator.of(context)
          .push<String>(new MaterialPageRoute(builder: (context) {
        return new SetPayPwdPage();
      }));
    } else {}
  }

  @override
  void initState() {
    super.initState();
    barModel.outSideCallback = focusNodeChange;
    getString(TOKEN).then((value) {
      token = value;
      card();
    });

    account = '';
    name = '';
    // account = APPLIC.userInfoMap['user_detail']['alipay_account'];
    // name = APPLIC.userInfoMap['user_detail']['truename']==null?"":APPLIC.userInfoMap['user_detail']['truename'];
    setState(() {});

    WidgetsBinding.instance.addObserver(this); //接收通知
    APPLIC.eventBus.on<GetCardEven>().listen((event) {
      getString(TOKEN).then((value) {
        token = value;
        card();
      });
    });
  }

  void focusNodeChange() {
    barModel.focusNodeListener();
    setState(() {});
  }

  @override
  void dispose() {
    barModel.removeFocusListeners();
    // TODO: implement dispose
    super.dispose();
  }

  put() async {
    if(money==''||money==null){
       Navigator.of(context).pop(1);
      Toast.toast(context, msg: '填写提现金额');
      return;
    }
    // if(double.parse(money)>4900){
    //    Navigator.of(context).pop(1);
    //   Toast.toast(context, msg: '最高提现4900元');
    //   return;
    // }
    
    Map map = new Map();
    map['token'] = token;
    map['account'] = account;
    map['truename'] = name;
    map['account_type'] = "1";
    map['money'] = money;
    map['sign_type'] = 'cdd.UserBalance.draw';
 Navigator.of(context).pop(1);
    print(map);
    Response<String> response =
        await HttpUtil().post(Api.DrawUrl, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    print(userMap);
    // Fluttertoast.showToast(msg: msg);
    Toast.toast(context, msg: msg);
    if (code == 0 && mounted) {
      Navigator.of(context).pop();
    }
  }

  card() async {
    //先判断银行卡有没有添加过关于支付宝的账号
    FormData data = new FormData.fromMap({'token': token});
    Response<String> response =
        await HttpUtil().post(Api.GetAccountListUrl, data: data);
    Map userMap = json.decode(response.data);
    print(userMap);
    int code = userMap["code"];
    String msg = userMap["msg"];
    if (code == 1 && mounted) {
      setState(() {
        List list = userMap['data']['list'];
        if (list.length == 1) {
          account = userMap['data']['list'][0]['account'];
          name = userMap['data']['list'][0]['truename'];
        }
      });
    }
  }
}
